//
//  OpenFileWithApplication.m
//  OpenThirdAppDemo
//
//  Created by Victor on 2018/7/31.
//  Copyright © 2018 Victor. All rights reserved.
//

#import "OpenFileWithApplication.h"

@implementation OpenFileWithApplication


/*
 获取支持打开文件的 APP 和 默认APP

 */
+ (NSMutableSet *)applicationsSetForItems:(NSArray *)itemsList defaultURL:(NSURL **)defaultAppURL
{

    NSMutableSet* applicationsSet = nil;
    NSMutableSet* setOfExtensions = [NSMutableSet setWithCapacity:0];
    NSMutableArray* setOfDefaultApp = [NSMutableArray arrayWithCapacity:0];
    NSInteger counter = 0;

    for(id item in itemsList)
    {
        counter++;

        NSString* fullPath = nil;
        assert([item isKindOfClass:[NSString class]]);
        fullPath = (NSString*)item;

        NSString* ext = [fullPath pathExtension];

        if ([setOfExtensions containsObject:ext])
        {
            continue;
        }else
        {
            [setOfExtensions addObject:ext];
        }

        NSURL* url = [NSURL fileURLWithPath: fullPath];

        //defaultAppURL
        NSURL* anURL = (NSURL*)CFBridgingRelease(LSCopyDefaultApplicationURLForURL((__bridge CFURLRef)url, kLSRolesAll, NULL));//LSGetApplicationForURL


        if (anURL)
        {
            if (![setOfDefaultApp containsObject:anURL])
            {
                [setOfDefaultApp addObject:anURL];
            }

            if ([setOfDefaultApp count] > 1 )
            {
                *defaultAppURL = nil;
            }
            else if ([setOfDefaultApp count] == 1 )
            {
                *defaultAppURL = [setOfDefaultApp firstObject];
            }

        }
        else
        {
            *defaultAppURL = nil;
        }

        //applicationsSet
        NSArray* arrayOfURLs = (NSArray*) CFBridgingRelease(LSCopyApplicationURLsForURL( (__bridge CFURLRef)url, kLSRolesAll));

        if (arrayOfURLs)
        {
            if (!applicationsSet)
            {
                applicationsSet = [NSMutableSet setWithArray: (NSArray*) arrayOfURLs];
            }else
            {
                [applicationsSet intersectSet: [NSSet setWithArray: (NSArray*) arrayOfURLs] ];
            }
        }
        else
        {
            [applicationsSet removeAllObjects];
            break;
        }
    }
    return applicationsSet;
}


//applyToAll 将改程序设置为 该文件类型的默认打开程序
+ (void)openItems:(NSArray <NSString *> *)itemsFullPaths withApplicationPath:(NSString *)applicationPath
             open:(BOOL)openWith applyToAll:(BOOL)applyToAll
{

    if (!applicationPath)
    {
        NSURL* defaultAppURL = nil;
        [OpenFileWithApplication applicationsSetForItems: itemsFullPaths defaultURL: &defaultAppURL];
        applicationPath = [defaultAppURL path];
    }

    if (!applicationPath)// no application found. Thus do nothing
    {
        return;
    }

    NSMutableArray* itemsArray = [NSMutableArray arrayWithCapacity:0];
    LSLaunchURLSpec launchSpec = {0};
    launchSpec.appURL = (__bridge CFURLRef)[NSURL fileURLWithPath: applicationPath isDirectory:YES];
    launchSpec.itemURLs = (__bridge CFArrayRef)itemsArray;
    launchSpec.launchFlags = kLSLaunchDefaults;

    for(NSString* fullPath in itemsFullPaths)
    {
        NSURL* itemURL = [NSURL fileURLWithPath: fullPath];

        [itemsArray addObject:itemURL];

        if (applyToAll)
        {
            NSBundle* appBundle = [NSBundle bundleWithPath: applicationPath];
            NSString* contentType = nil;
            NSError* err = nil;
            [itemURL getResourceValue:&contentType forKey:NSURLTypeIdentifierKey error:&err];

            if (nil == err)
            {
                OSStatus status = LSSetDefaultRoleHandlerForContentType ((__bridge CFStringRef)contentType,kLSRolesAll,(__bridge CFStringRef)[appBundle bundleIdentifier]);
                if ( noErr != status)
                {
                    NSLog(@"LSSetDefaultRoleHandlerForContentType ERROR: %d", status);
                }

            }
        }
    }

    OSStatus status = noErr;
    if (openWith && [itemsArray count])
    {
        status = LSOpenFromURLSpec(&launchSpec,NULL);
        if ( noErr != status)
        {
            NSLog(@"LSOpenFromURLSpec ERROR: %d", status);
        }
    }

    //assert(status==noErr);
}


@end
